package com.hemaapp.yjnh.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.ViewPagerFragment;
import com.hemaapp.yjnh.activity.BookOrderDetailActivity;
import com.hemaapp.yjnh.activity.CommentProductionActivity;
import com.hemaapp.yjnh.adapter.BookOrderListAdapter;
import com.hemaapp.yjnh.adapter.RecyclerTenDecoration;
import com.hemaapp.yjnh.listener.OrderItemClickListener;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.Order;
import com.hemaapp.yjnh.bean.User;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomRefreshLoadmoreLayout;

/**
 * 预约订单列表
 *
 */
public class BookOrderListFragment extends ViewPagerFragment implements OrderItemClickListener{

    private RefreshLoadmoreLayout parentLayout;
    private RecyclerView recyclerView;

    private User user;
    private int page = 0;
    private BookOrderListAdapter adapter;
    private ArrayList<Order> orders = new ArrayList<>();
    private String keytype;//订单的类型：	1:全部；2:待支付；3:待发货；4:待收货；5:待评价；6:待确认

    @Override
    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.fragment_viewpager_refresh_recycler);
        user = BaseApplication.getInstance().getUser();
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if (savedInstanceState != null) {
            keytype = savedInstanceState.getString("keytype");
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString("keytype", keytype);
        super.onSaveInstanceState(outState);
    }

    public void setType(String type) {
        this.keytype = type;
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ORDER_SAVEOPERATE:
            case ORDER_LIST:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ORDER_SAVEOPERATE:
            case ORDER_LIST:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ORDER_SAVEOPERATE:
                String keytype = netTask.getParams().get("keytype");
                if (keytype.equals("1")) {
                    XtomToastUtil.showShortToast(getActivity(), "删除订单成功!");
                }else if (keytype.equals("3")) {
                    XtomToastUtil.showShortToast(getActivity(), "取消预约成功!");
                }
                EventBusMsg msg = new EventBusMsg();
                msg.setType(EventBusConfig.UPDATE_ORDER);
                EventBus.getDefault().post(msg);
                break;
            case ORDER_LIST:
                String page = netTask.getParams().get("page");
                HemaPageArrayResult<Order> iResult = (HemaPageArrayResult<Order>) baseResult;
                if (iResult == null || iResult.getObjects() == null)
                    return;
                if ("0".equals(page)) {// 刷新
                    parentLayout.refreshSuccess();
                    if (iResult.getObjects().size() == 0)
                        parentLayout.setLoadmoreable(false);
                    else
                        parentLayout.setLoadmoreable(true);
                    orders.clear();
                    orders.addAll(iResult.getObjects());
                } else {// 更多
                    parentLayout.loadmoreSuccess();
                    orders.addAll(iResult.getObjects());
                    if (iResult.getObjects().size() > 0) {
                        orders.addAll(iResult.getObjects());
                    } else {
                        parentLayout.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(getActivity(), "已经到最后啦");
                    }
                }
                refreshData();
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ORDER_SAVEOPERATE:
                String keytype = netTask.getParams().get("keytype");
                if (keytype.equals("1")) {
                    XtomToastUtil.showShortToast(getActivity(), "删除订单失败,"+baseResult.getMsg());
                }else if (keytype.equals("3")) {
                    XtomToastUtil.showShortToast(getActivity(), "取消预约失败,"+baseResult.getMsg());
                }else
                    XtomToastUtil.showShortToast(getActivity(), "操作失败," + baseResult.getMsg());
                break;
            case ORDER_LIST:
                XtomToastUtil.showShortToast(getActivity(), "获取订单失败," + baseResult.getMsg());
                String page = netTask.getParams().get("page");
                if ("0".equals(page))// 刷新
                    parentLayout.refreshFailed();
                else
                    parentLayout.loadmoreFailed();
                refreshData();
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case ORDER_SAVEOPERATE:
                String keytype = netTask.getParams().get("keytype");
                if (keytype.equals("1")) {
                    XtomToastUtil.showShortToast(getActivity(), "删除订单失败,请稍后再试");
                }else if (keytype.equals("3")) {
                    XtomToastUtil.showShortToast(getActivity(), "取消预约失败,请稍后再试");
                }else
                    XtomToastUtil.showShortToast(getActivity(), "操作失败,请稍后再试");
                break;
            case ORDER_LIST:
                XtomToastUtil.showShortToast(getActivity(), "获取订单失败,请稍后再试");
                String page = netTask.getParams().get("page");
                if ("0".equals(page))// 刷新
                    parentLayout.refreshFailed();
                else
                    parentLayout.loadmoreFailed();
                refreshData();
                break;
        }
    }

    private void refreshData() {
        if (adapter == null) {
            adapter = new BookOrderListAdapter(getActivity(), orders, this);
            recyclerView.setAdapter(adapter);
            recyclerView.addItemDecoration(new RecyclerTenDecoration(getActivity()));
        }else
            adapter.notifyDataSetChanged();
    }

    @Override
    protected void findView() {
        parentLayout = (RefreshLoadmoreLayout) findViewById(R.id.refreshLoadmoreLayout);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    }

    @Override
    protected void setListener() {
        parentLayout.setOnStartListener(new XtomRefreshLoadmoreLayout.OnStartListener() {
            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
                page = 0;
                getNetWorker().orderList(user.getToken(), "3", keytype, page + "");
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
                page++;
                getNetWorker().orderList(user.getToken(), "3", keytype, page + "");
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
    }

    @Override
    public void onItemClickListener(int position) {
        Intent it = new Intent(getActivity(), BookOrderDetailActivity.class);
        it.putExtra("order_id", orders.get(position).getId());
        startActivity(it);
    }

    @Override
    public void onPay(int position) {
        Intent itCommit = new Intent(getActivity(), CommentProductionActivity.class);
        itCommit.putExtra("goods_id", orders.get(position).getChildren().get(0).getId());
        startActivity(itCommit);
    }

    @Override
    public void onRefusePay(final int position) {
        HemaButtonDialog hbDialog = new HemaButtonDialog(getActivity());
        hbDialog.setText("确认删除订单吗？");
        hbDialog.setLeftButtonText("取消");
        hbDialog.setRightButtonText("确定");
        hbDialog.setRightButtonTextColor(getResources().getColor(
                R.color.theme_orange));
        hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

            @Override
            public void onRightButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
                getNetWorker().orderSaveoperate(user.getToken(),
                        orders.get(position).getId(), "1", "无", "无", "无", "无");
            }

            @Override
            public void onLeftButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
            }
        });
    }

    /**朋友代付
     * @param position
     */
    @Override
    public void onPayBehalf(int position) {
    }

    @Override
    public void onCancel(final int position) {
        String enable = orders.get(position).getReturn_enable();
        // 预约订单是否能退款 0否；1是
        if (enable.equals("1")) {
            HemaButtonDialog hbDialog = new HemaButtonDialog(getActivity());
            hbDialog.setText("确认取消预约吗？");
            hbDialog.setLeftButtonText("取消");
            hbDialog.setRightButtonText("确定");
            hbDialog.setRightButtonTextColor(getResources().getColor(
                    R.color.theme_orange));
            hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

                @Override
                public void onRightButtonClick(HemaButtonDialog dialog) {
                    dialog.cancel();
                    getNetWorker().orderSaveoperate(user.getToken(),
                            orders.get(position).getChildren().get(0).getId(), "3", "无", "无", "无", "无");
                }

                @Override
                public void onLeftButtonClick(HemaButtonDialog dialog) {
                    dialog.cancel();
                }
            });
        } else {
            Dialog dialog2 = new Dialog(getActivity(), R.style.dialog);
            View view = getActivity().getLayoutInflater().inflate(
                    R.layout.dialog_refuse_aftersale, null);
            TextView tv_phone = (TextView) view.findViewById(R.id.tv_phone);
            final String number = BaseApplication.getInstance().getSysInitInfo()
                    .getSys_service_phone();
            tv_phone.setText(number);
            tv_phone.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri
                            .parse("tel:" + number));
                    startActivity(intent);
                }
            });
            dialog2.setCancelable(true);
            dialog2.setContentView(view);
            dialog2.show();
        }


    }

    @Override
    public void onReceive(final int position) {
    }

    @Override
    public void onAgreeReturn(final int position) {
    }

    @Override
    public void onRefuseReturn(final int position) {
    }

    @Override
    public void onDeliveryGoods(final int position) {
    }

    @Override
    public void fetchData() {
        getNetWorker().orderList(user.getToken(), "3", keytype, page + "");
    }

    @Subscribe
    public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.UPDATE_ORDER) {
            page = 0;
            getNetWorker().orderList(user.getToken(), "3", keytype, page + "");
        }
    }
}
